import json

from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from django.http import JsonResponse
from django.views import View

from apps.carts.utils import merge_cart_cookie_to_redis
from apps.oauth.models import OAuthQQUser
from apps.users.models import User


# Create your views here.


class QQAuthURLVie(View):

    def get(self, request):
        next = request.GET.get('next')
        oauth = OAuthQQ(client_id='101474184', client_secret='c6ce949e04e12ecc909ae6a8b09b637c',
                        redirect_uri='http://www.meiduo.site:8080/oauth_callback.html', state='xxxx')

        login_url = oauth.get_qq_url()

        return JsonResponse(data={'code': 0, 'errmsg': '', 'login_url': login_url})


class QQAuthUserView(View):

    def get(self, request):
        code = request.GET.get('code')

        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})

        oauth = OAuthQQ(client_id='101474184', client_secret='c6ce949e04e12ecc909ae6a8b09b637c',
                        redirect_uri='http://www.meiduo.site:8080/oauth_callback.html', state='xxxx')

        access_token = oauth.get_access_token(code)

        openid = oauth.get_open_id(access_token)

        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            return JsonResponse({'code': 300, 'errmsg': '未绑定', 'access_token': openid})
        else:

            login(request, qq_user.user)

            response = JsonResponse({'code': 0, 'errmsg': 'ok'})

            merge_cart_cookie_to_redis(request, qq_user.user, response)

            response.set_cookie('username', qq_user.user.username)

            return response

    def post(self, request):
        data = json.loads(request.body.decode())

        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        openid = data.get('access_token')

        if not all([mobile, password, sms_code, openid]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})

        try:
            user = User.objects.get(mobile=mobile)

        except User.DoesNotExist:
            user = User.objects.create_user(username=mobile, mobile=mobile, openid=openid)

        else:
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '账户/密码错误'})

        login(request, user)

        response = JsonResponse({'code': 0, 'errmsg': ''})
        response.set_cookie('username', user.username)

        return response
